/**
 * Created by lmn98 on 2017/5/19.
 */
var express = require('express');
var router = express.Router();
var err = require('../my_modules/error.js');
var config = require('../config');
var db = require('../my_modules/my_sequlize');
//建立root文件夹
var fs = require('fs');
var path=require('path');
if(!fs.existsSync(path.resolve(config.file.root))){
    fs.mkdirSync(path.resolve(config.file.root));
}
if(!fs.existsSync(path.resolve(config.file.temp))){
    fs.mkdirSync(path.resolve(config.file.temp));
}
//字节数转容量
var byteToStr = function (size) {
    if(size/1000<1) return size.toFixed(2) + 'B';
    else if(size/1000000<1) return (size/1000).toFixed(2) + 'KB';
    else if(size/1000000000<1) return (size/1000000).toFixed(2) + 'MB';
    else return (size/1000000000).toFixed(2) + 'GB';
};
//所有文件空间统计 ok
var calculateAllSize = function (home) {
    var allFileSize = 0;
    var addSize = function (dir) {
        fs.readdirSync(dir).forEach(function (_file) {
            var stat = fs.statSync(path.join(dir,_file));
            if(stat.isFile()){
                allFileSize += stat.size;
            }else{
                addSize(path.join(dir, _file))
            }
        })
    };
    addSize(home);
    return allFileSize;
};
//按照文件名判断文件类型
var fileType = function (name) {
    var suffix = name.split('.');
    suffix = suffix[suffix.length-1].toUpperCase();
    if(suffix === 'JPG'||suffix === 'PNG'||suffix === 'GIF'){
        return 'img'
    }else if(suffix === 'AVI'||suffix === 'MP4'||suffix === 'MKV'
        ||suffix === 'WMA'||suffix === 'RMVB'||suffix === 'RM'){
        return 'video'
    }else{
        return 'unknown'
    }
};
//按照文件名搜索文件
router.get('/search/:name', function (req, res) {
    var name = req.params.name;
    if(!name){ res.json();return; }
    var files = [];
    var search = function (dir) {
        var names = fs.readdirSync(dir);
        names.forEach(function (_name) {
            if(fs.statSync(path.join(dir,_name)).isDirectory()){
                if(_name.indexOf(name)>=0){
                    files.push({
                        folder: true,
                        name: _name,
                        dir: dir.split(req.session.root)[1].replace(/\\/g,',').replace(/\//g,',')
                    })
                }
                search(path.join(dir,_name));
            }else{
                if(_name.indexOf(name)>=0){
                    files.push({
                        name: _name,
                        dir: dir.split(req.session.root)[1].replace(/\\/g,',').replace(/\//g,',')
                    })
                }
            }
        })
    };
    search(path.resolve(req.session.root+req.session.dir));
    res.json(files);
});
//按照类型搜索文件
router.get('/searchByType/:type', function (req, res) {
    var type = req.params.type;
    if(!type){ res.json(err.paraErr);return; }
    var files = [];
    var search = function (dir) {
        var names = fs.readdirSync(dir);
        names.forEach(function (_name) {
            var state = fs.statSync(path.join(dir,_name));
            if(state.isDirectory()){
                search(path.join(dir,_name));
            }else{
                if(type === fileType(_name)){
                    files.push({
                        name: _name,
                        size: byteToStr(state.size),
                        ctime: state.ctime,
                        dir: dir.split(req.session.root)[1]
                    })
                }
            }
        })
    };
    search(path.resolve(req.session.root+req.session.dir));
    res.json(files);
});
//查看文件夹 ok
router.get('/open/:dir', function (req, res) {
    var dir = req.params.dir;
    var sortname = req.query.sortname,
        sortorder = req.query.sortorder;
    if(req.session.fileUploaded){
        req.session.fileUploaded = false;
        calculateAllSize(req.session.root);
    }
    if(!req.session.allFileSize) req.session.allFileSize = calculateAllSize(req.session.root);
    var readDir = function (_path) {
        var _files = fs.readdirSync(_path);
        var result = [];
        _files.forEach(function (file) {
            var states = fs.statSync(path.join(_path,file));
            if(states.isDirectory()){
                result.push({
                    count: fs.readdirSync(path.join(_path,file)).length,
                    name: file,
                    ctime: states.ctime,
                    dir : _path.split(req.session.root)[1]
                })
            }else{
                result.push({
                    name: file,
                    size: byteToStr(states.size),
                    ctime: states.ctime,
                    dir: _path.split(req.session.root)[1]
                })
            }
        });
        var order = -1;
        if(sortorder=='asc')order = -1;
        else order = 1;
        if(sortname=='name'){
            result.sort(function(a, b){
                return a.name.localeCompare(b.name)*order;
            })
        }else if(sortname=='ctime'){
            result.sort(function (a, b) {
                if(a.ctime > b.ctime) return order;
                else return order*-1;
            })
        }
        var _root ;
        if(_path.indexOf('\\')>=0) _root = req.session.root.replace(/\//g,'\\');
        return {
            disk: {limit: config.file.limitByte, used: req.session.allFileSize},
            dir: _path.split(_root)[1],
            list: result
        };
    };
    if(dir==='_home'){
        req.session.dir = '/';
    }else if(dir!=='refresh'){
        dir = dir.replace(/\,/g,'/');
        if(dir.substring(0,1)==='/') dir = dir.substring(1);
        req.session.dir = '/' +dir;
    }
    res.json(readDir(path.resolve(req.session.root+req.session.dir)));
});
//剪贴板 ok
var copy = function( name, src, dst ,callback){
    if(!fs.existsSync(src+'/'+name)){
        callback();return;
    }
    var readable, writable;
    var st = fs.statSync(src+'/'+name);
    if( st.isFile() ){
        if(fs.existsSync(path.resolve(dst +'/'+name))){
            callback();
            return;
        }
        readable = fs.createReadStream( src +'/'+name);
        writable = fs.createWriteStream( dst +'/'+name);
        readable.pipe( writable ,{ end: false});
        readable.on('end', function () {
            writable.end();
            callback(name);
        })
    }else if( st.isDirectory() ){
        var files = fs.readdirSync(src+'/'+name);
        var count = files.length;
        files.forEach(function (file) {
            exists(file, src+'/'+name,dst+'/'+name, function(){
                if(--count == 0) callback(name);
            });
        })
    }
};
var exists = function(name, src, dst, callback ){// 在复制目录前需要判断该目录是否存在，不存在需要先创建目录
    fs.exists( dst, function( exists ){
        if( exists ){
            copy(name, src, dst ,callback);
        }
        else{
            fs.mkdir( dst, function(){
                copy( name, src, dst ,callback);
            });
        }
    });
};
router.post('/clipboard', function (req, res) {
    var data = req.body;
    data.dir = req.session.dir+'';
    req.session.clipboard = data;
    res.json();
});
router.post('/paste', function (req, res) {
    var clip = req.session.clipboard;
    if(clip.dir != req.session.dir){
        for(var i=0,l=clip.files.length;i<l;i++){
            exists(
                clip.files[i],
                path.resolve(req.session.root+clip.dir),
                path.resolve(req.session.root+req.session.dir),
                function (file) {
                    if(clip.type==1 && file){
                        deleteFile(path.resolve(req.session.root+clip.dir+'/'+file))
                    }
                }
            );
        }
    }
    res.json();
});
//重命名 ok
router.put('/:name', function (req, res) {
    var data = req.body;
    if(!data.newName) res.json(err.paraErr);
    else{
        var srcPath = path.resolve(req.session.root+req.session.dir+'/'+req.params.name);
        if(fs.existsSync(srcPath))
            fs.renameSync(
                srcPath,
                path.resolve(req.session.root+req.session.dir+'/'+data.newName)
            );
        res.json();
    }
});
//删除文件 ok
var deleteFile = function (_path) {
    if(!fs.existsSync(_path)) return;
    if(fs.statSync(_path).isDirectory()){
        var files = fs.readdirSync(_path);
        files.forEach(function (file) {
            deleteFile(path.join(_path,file))
        });
        fs.rmdirSync(_path);
    }else{
        fs.unlinkSync(_path)
    }
};
router.delete('/:dir', function (req, res) {
    var dirs = req.params.dir.replace(/\,/g,'/').split(';');
    for(var i=0,l=dirs.length;i<l;i++){
        if(!dirs[i]) continue;
        var _path = path.resolve(req.session.root+dirs[i]);
        deleteFile(_path);
    }
    calculateAllSize(req.session.root);
    res.json(err.success);
});
//新建文件夹 ok
router.post('/mkdir', function (req, res) {
    var data = req.body;
    if(!data || !data.name) res.status(400).json(err.paraErr);
    else{
        var tarDir = path.join(req.session.root+req.session.dir , data.name);
        if(!fs.existsSync(tarDir)) {
            fs.mkdirSync(tarDir);
            res.json(true)
        }else res.json(err.nameExist);
    }
});
var Busboy = require('busboy');
//文件上传 ok
router.post('/upload',function (req, res) {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename) {
        var saveTo = path.join(req.session.root + req.session.dir, path.basename(filename));
        file.pipe(fs.createWriteStream(saveTo));
    });
    busboy.on('finish', function () {
        req.session.fileUploaded = true;
        res.writeHead(303, { Connection: 'close', Location: '/#/files' });
        res.end();
    });
    return req.pipe(busboy);
});
//临时bt文件上传 ok
router.post('/upload/bt',function (req, res) {
    var busboy = new Busboy({ headers: req.headers });
    var fileName = '',saveTo;
    busboy.on('file', function(fieldname, file) {
        fileName = Math.random().toFixed(4)*10000+'_'+new Date().getTime();
        saveTo = path.join(config.file.temp, fileName+'.torrent');
        file.pipe(fs.createWriteStream(saveTo));
    });
    busboy.on('finish', function () {
        req.session.fileUploaded = true;
        res.writeHead(303, { Connection: 'close', Location: '/#/createOfflineBt/'+fileName});
        res.end();
    });
    return req.pipe(busboy);
});
//文件下载
router.get('/download', function (req, res) {
    res.download(path.resolve(path.join(req.session.root,req.query.dir)));
});
//获取文件夹列表
router.get('/dir/:name', function (req, res) {
    var dirName = req.params.name;
    dirName = dirName.replace(/\,/g,'/');
    var _path = path.resolve(req.session.root+dirName);
    var _files = fs.readdirSync(_path);
    var result = [];
    _files.forEach(function (file) {
        var states = fs.statSync(path.join(_path,file));
        if(states.isDirectory()){
            result.push({
                name: file,
                dir: req.params.name+file+','
            })
        }
    });
    res.json(result);
});

module.exports = router;